package com.self.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BeanCpoyUtils {
    /**
     * 对象拷贝
     *
     * @param <T>
     * @param original 原对象
     * @param t        拷贝目标
     * @return 拷贝目标
     */
    public static <T> T beanCopy(Object original, T t) {
        if (null == original) {
            return null;
        }
        BeanCopier beanCopier = BeanCopier.create(original.getClass(), t.getClass(), true);
        Converter converter = getConverter(false);
        try {
            beanCopier.copy(original, t, converter);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return t;
    }

    /**
     * 获取Converter
     *
     * @return Converter
     */
    public static Converter getConverter(boolean flag) {
        Converter converter = new Converter() {
            @Override
            public Object convert(Object value, Class target, Object o1) {
                {
                    if (null == value && flag) {
                        if (!target.equals(String.class)) {
                            if (target.equals(List.class)) {
                                return new ArrayList<>();
                            }
                            return null;
                        }
                        return "";
                    }
                    if (null != value) {
                        String s = value.toString();
                        if (target.equals(int.class) || target.equals(Integer.class)) {
                            return Integer.parseInt(s);
                        }
                        if (target.equals(long.class) || target.equals(Long.class)) {
                            return Long.parseLong(s);
                        }
                        if (target.equals(float.class) || target.equals(Float.class)) {
                            return Float.parseFloat(s);
                        }
                        if (target.equals(double.class) || target.equals(Double.class)) {
                            return Double.parseDouble(s);
                        }
                    }
                    return value;
                }
            }
        };
        return converter;
    }

}
